package com.atguigu.study.question;

import java.util.concurrent.CountDownLatch;

class MyNumber
{
    //测试volatile不保证原子性
    volatile int number = 0;
    //本方法没有加synchronized
    public void add()
    {
        number++;
    }
}

/**
 * @auther zzyybs@126.com
 * @Date 2025-04-27 16:07
 * @Description: TODO
 */

public class VolatileNotAtomicDemo
{
    public static final int NUMBER200 = 200;

    public static void main(String[] args) throws InterruptedException
    {
        MyNumber myNumber = new MyNumber();
        CountDownLatch countDownLatch = new CountDownLatch(NUMBER200);


        for (int i = 1; i <=NUMBER200; i++) {
            new Thread(() -> {
                for (int j = 1; j <=NUMBER200; j++) {
                    myNumber.add();
                }
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+"\t"+myNumber.number);

    }
}


